package ru.ncedu.robot;

import java.util.Random;

public class Head implements Runnable{
	private Body body;

	public Head(Body parent){
		body = parent;
	}

	private void msgToFoot(Foot f, Message m) throws InterruptedException{
		f.lock.lock();
		try{
			while (f.state != State.WAIT){ 
				//System.out.println("Waiting WAIT from " + f.name);
				f.waiting.await();
			}
			f.msg = m;
			f.waiting.signal();
			while (!f.done) {
				//System.out.println("Waiting WAIT from " + f.name);
				f.waiting.await();
			}
		}
		finally{
			f.lock.unlock();
		}
	}
	
	@Override
	public void run() {
		System.out.println("Head was executed!");
		
		while(!Thread.interrupted()){
			try {				
				for (Foot i: body.getFeet()){
					msgToFoot(i, Message.FORWARD);
					Thread.sleep((long) ((new Random().nextDouble())*200 + 100));
				}						
			} 
			catch (InterruptedException e) {
				break;
			}
		}
	}

	public void setParent(Body parent) {
		this.body = parent;		
	}

	
}
